package com.objectoriented.tang.service;

import com.objectoriented.tang.pojo.Player;

import java.util.Arrays;
import java.util.PriorityQueue;

public class MatchQueue extends Thread{

    private int R_count=0;

    private static PriorityQueue<RequestUser> requestUsers = new PriorityQueue<>();

    private static Player player;

    private static boolean init=true;

    public  void add(RequestUser requestUser)
    {
        System.out.println("新元素加入队列"+requestUser.getUID());
        requestUsers.offer(requestUser);
        requestUser.waitFor();
        if(init){
            this.start();
            init = false;
        }
    }
    public int cancel(int UID){
        for (RequestUser x : requestUsers) {
            if(x.getUID()==UID)requestUsers.remove(x);
            System.out.println(x);
        }
        return 1;
    }

    public  Player getPlayer() {
        return player;
    }

    @Override
    public void run() {
        super.run();
        while(true)
        {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }



            if(requestUsers.size()>=2){
                System.out.println("队列元素个数为"+requestUsers.size());
                RequestUser UA=requestUsers.poll();
                RequestUser UB=requestUsers.poll();
                System.out.println("UA"+UA.getUID());
                System.out.println("UB"+UB.getUID());
                if(UA.getUID()==UB.getUID()){

                }
                player = new Player(UB.getUID(),1,R_count);
                UA.awake();
                try {
                    sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                player = new Player(UA.getUID(),2,R_count++);
                UB.awake();
            }
            else System.out.println("队列元素不足,无法匹配,等待新的请求");
        }
    }
}
